import axios, {AxiosRequestConfig, AxiosResponse} from 'axios'
// 引入loading组件
import {ElLoading, ElMessage} from 'element-plus'


// 默认显示loading
const DEFAULT_LOADING = true
let loadingObj;

interface ResponseData {
    code: number;
    data: any;
    msg: string;
}


// 创建axios实例
const service = axios.create({
    baseURL: 'http://127.0.0.1:8000/api', // api的base_url
    // baseURL: 'http://yyydm-api.yunshangdaomi.com/api', // api的base_url
    timeout: 5000 // 请求超时时间
})
// 请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        let _token = localStorage.getItem('token');
        config.headers['Authorization'] = "Bearer " + _token;
        if (DEFAULT_LOADING) {
            // 添加loading
            loadingObj = ElLoading.service({
                lock: true,
                text: '加载中...',
                fullscreen: true,
                // background: 'rgba(0, 0, 0, 0.5)'
            })
        }

        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)
// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        // 所有的请求,将loading移除
        loadingObj?.close();
        const res = response.data as ResponseData
        if(res.code==10001){
            window.location.href='/login';
            return ;
        }
        if (res.code !== 0) {
            // 统一处理错误
            ElMessage.error(res.msg)
            return res;
            // return Promise.reject(res.msg || '请求失败')
        } else {
            return res || {}
        }
    },
    (error: any) => {
        // 统一处理错误
        // 所有的请求,将loading移除
        loadingObj?.close();
        ElMessage.error('网络错误');
        return false;
        // return Promise.reject(error)
    }
)
// 封装get请求
export const get = (url: string, params?: any) => {
    return service.get(url, {params})
}
// 封装post请求
export const post = (url: string, data?: any) => {
    return service.post(url, data)
}